package com.server.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.database.bean.User;
 
//@javax.servlet.annotation.WebFilter(urlPatterns = {"/*"}, description = "Session Checker Filter")
public class WebFilter implements Filter {
    private FilterConfig config = null;
 
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        config.getServletContext().log("Initializing SessionCheckerFilter");
    }
 
    public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)
            throws ServletException, IOException {
 
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession httpSession = null;
        User user=null;
       
        if (request.getSession(false)!=null){
        	httpSession=request.getSession(false);
        	if (httpSession.getAttribute("user")!=null)
            	user = (User)httpSession.getAttribute("user");
        }

		String url=request.getRequestURI();
        //System.out.println("URL:"+url);
        //System.out.println("User:"+user);
 
        //
        // Check to see if user's session attribute contains an attribute
        // named AUTHENTICATED. If the attribute is not exists redirect
        // user to the login page.
        //
        if (user!=null || url.endsWith("game/") || url.endsWith("css.xhtml") || url.endsWith("js.xhtml") || url.endsWith("index.xhtml")|| url.endsWith("noAuthorization.xhtml")) {
        	//System.out.println("OK");
        }
        else{
        	response.sendRedirect(request.getContextPath()+"/faces/noAuthorization.xhtml");
        }
        chain.doFilter(req, res);
        
    }
 
    public void destroy() {
        config.getServletContext().log("Destroying SessionCheckerFilter");
    }
}
